from actions.action import Action
from activity import Activity


class StartActivityAction(Action):

    def entrance(self, activity: Activity, config, driver):
        # 获取当前activity_name
        current_activity_name = self._get_activity(config, driver)
        new_activity = Activity(current_activity_name)

        if activity is not None:
            self._relationship(activity, new_activity)
            activity.clear_element()

        # 存储到类对象
        key = new_activity.key()
        if key not in Activity.activities:
            Activity.activities[key] = new_activity

        # TODO 记录操作和activity
        new_activity = Activity.activities[key]
        # elements = collections.OrderedDict()
        # walk_element(elements, driver.dump())
        # new_activity.elements = elements

        return new_activity

    def _relationship(self, old_activity: Activity, new_activity: Activity):
        # if old_activity.element is not None:

        if self._has_in_parents(old_activity, new_activity):
            # 如果新activity在父节点中找到了，就不管
            return
        if new_activity in [x[1] for x in old_activity.next]:
            # 如果新activity，在子节点中找到了。暂时也不管
            index = [x[1] for x in old_activity.next].index(new_activity)
            new_activity.parent = [x[1] for x in old_activity.next][index].parent
            return

        # 都没找到的情况下，记录之前的点击的控件和新的activity
        old_activity.next.append((old_activity.element, new_activity))
        new_activity.parent = old_activity

    def _has_in_parents(self, old_activity: Activity, new_activity: Activity):
        if new_activity == old_activity:
            new_activity.parent = old_activity.parent
            return True

        if old_activity.parent is None:
            return False

        if new_activity != old_activity.parent:
            return self._has_in_parents(old_activity.parent, new_activity)
        else:
            new_activity.parent = old_activity.parent.parent
            return True

    def _get_activity(self, config, driver):
        activity_name = None
        index = 0
        while index < 5:
            activity_name = self._get_activity_name(driver)
            if self._check(activity_name, config):
                break
            else:
                index += 1
                driver.back()

        if index >= 5:
            raise Exception("")

        return activity_name

    def _check(self, activity_name, config):
        if "start_app" not in config:
            return True
        package = config["start_app"]
        if package in activity_name:
            return True
        else:
            return False

    def _get_activity_name(self, driver):
        activity_name = None
        while activity_name is None:
            activity_name = driver.get_activity()
        return activity_name
